<?php
/**
 * User: YL
 * Date: 2019/09/12
 */

namespace App\Middleware;

use Closure;
use Illuminate\Http\Request;
use restful\ResultCode;
use restful\ResultException;
use restful\traits\ResultThrow;
use restful\utils\Dispatch;
use restful\utils\Env;
use restful\utils\Token;

class CheckToken
{
    use ResultThrow;

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws ResultException
     */
    public function handle(Request $request, Closure $next)
    {
        $token = Token::get();
        $controller = Dispatch::getInstance($request)->getController();
        $method = Dispatch::getInstance($request)->getMethod();
        $methods = Dispatch::run($controller, 'getNoNeedLoginMethod');

        // 需要验证token
        if (! in_array($method, $methods) || ! empty($token)) {
            // 判断token是否存在
            if (empty($token)) {
                $this->error('token不存在', ResultCode::TOKEN_NO_EXISTS);
            }

            // 解析token
            $parse = Token::parse($token);

            // 验证token
            $verify = Token::verify($parse);
            if ($verify !== true) {
                $this->error($verify[1], $verify[0]);
            }

            // 解析[加密字符, 加密时间]
            [$str, $time] = $parse;

            // 判断token是否有效 TODO: 通过加密字符验证用户是否存在
            if (true) {
                $request->tokenData = [
                    'info' => [],
                ];
            }

            // 判断是否刷新token
            $noticeTime = Env::get('token.notice_refresh_time', 0);
            if ((time() - $time) >= $noticeTime) {
                // 设置刷新的token
                $request->refreshToken = Token::create($str);
            }
        }

        return $next($request);
    }
}
